package com.bed.lovewithpatientbed.controller;

import com.bed.lovewithpatientbed.service.IWorkMessageService;
import com.bed.lovewithpatientbed.util.KaptchaUtil;
import com.bed.lovewithpatientbed.common.LoginSubjectType;
import com.bed.lovewithpatientbed.common.token.CustomUsernamePasswordToken;
import com.bed.lovewithpatientbed.pojo.WorkerMessage;
import com.bed.lovewithpatientbed.util.KaptchaUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName LoginController.java
 * @Description 非普通用户（Worker）登录
 */
@Slf4j
@Controller
public class LoginController {

    // Kaptcha 操作类
    private DefaultKaptcha defaultKaptcha;
    @Resource
    IWorkMessageService workMessageService;

    @Autowired
    public void setDefaultKaptcha(DefaultKaptcha defaultKaptcha) {
        this.defaultKaptcha = defaultKaptcha;
    }

    @PostMapping("/login")
    @ResponseBody
    public Map<String, Object> login(HttpSession httpSession,  WorkerMessage workerMessage, String verifyCode) {
        Map<String, Object> responseMap = new HashMap<>();
        WorkerMessage workerMessage1 = workMessageService.selectByPhoneAndPwd(workerMessage);
        httpSession.setAttribute("workerMessage",workerMessage1);
        if (workerMessage == null) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "登录请求参数错误");
            return responseMap;
        }

        // 获取验证码
        String verificationCode = (String) httpSession.getAttribute(KaptchaUtil.KAPTCHA_SESSION_KEY);
        if (verificationCode == null || "".equals(verificationCode)) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "验证码读取错误");
            return responseMap;
        }

        // 验证码校验
        if (!KaptchaUtil.checkVerificationCode(verificationCode, verifyCode)) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "验证码输入错误");
            return responseMap;
        }

        // 获取主体对象
        Subject subject = SecurityUtils.getSubject();
        // 新建Token
        // UsernamePasswordToken usernamePasswordToken =
        //         new UsernamePasswordToken(workerMessage.getWorkMessagePhone(), workerMessage.getWorkMessagePassword());
        CustomUsernamePasswordToken usernamePasswordToken =
                new CustomUsernamePasswordToken(workerMessage.getWorkMessagePhone(),
                        workerMessage.getWorkMessagePassword(),
                        LoginSubjectType.SYSTEM_USER);

        try {
            // 登录认证
            subject.login(usernamePasswordToken);
            responseMap.put("result", true);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            responseMap.put("result", false);
            responseMap.put("errorMsg", "用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            responseMap.put("result", false);
            responseMap.put("errorMsg", "密码错误");
        }catch (Exception e){
            e.printStackTrace();
            responseMap.put("result", false);
            responseMap.put("errorMsg", "登陆失败");
        }
        // 从 session 移除验证码
        httpSession.removeAttribute(KaptchaUtil.KAPTCHA_SESSION_KEY);
        log.info("{} 请求登录，账号为：{}，登录结果：{}，失败原因：{}",
                LoginSubjectType.SYSTEM_USER.toString(),
                workerMessage.getWorkMessagePhone(),
                responseMap.get("result"),
                responseMap.get("errorMsg"));

        return responseMap;
    }

    @GetMapping("/getVerificationCode")
    public void getVerificationCode(HttpSession httpSession, HttpServletResponse response) {
        System.out.println("LoginController.getVerificationCode");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 生成验证码文字
        String verificationCodeText = defaultKaptcha.createText();
        // 验证码文字存入HttpSession
        httpSession.setAttribute(KaptchaUtil.KAPTCHA_SESSION_KEY, verificationCodeText);

        // 根据文字生成图片
        BufferedImage verificationCodeImage = defaultKaptcha.createImage(verificationCodeText);
        ServletOutputStream responseOutputStream = null;
        try {
            // 获取输出流
            responseOutputStream = response.getOutputStream();
            // 向客户端写出
            ImageIO.write(verificationCodeImage, "jpg", responseOutputStream);
            responseOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (responseOutputStream != null) {
                try {
                    responseOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/getLoginUserInfo")
    @ResponseBody
    public Map<String, Object> getLoginUserInfo() {
        Subject subject = SecurityUtils.getSubject();
        WorkerMessage principal = (WorkerMessage) subject.getPrincipal();
        if (principal != null) {
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("code", 0);
            responseMap.put("msg", "success");
            responseMap.put("data", principal);

            return responseMap;
        }

        return null;
    }

    @GetMapping("/logout")
    @ResponseBody
    public String logout() {
        System.out.println("LoginController.logout");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出用户
        return "success";
    }
}
